package com.linwen.excise.leetcode;

/**
 * @ClassName _21合并两个有序链表
 * @Description TODO
 * @Author zero
 * @DATE 2024/10/7 7:19 PM
 * @Version 1.0
 */
public class _21合并两个有序链表 {
    public static void main(String[] args) {
        _21合并两个有序链表 inst = new _21合并两个有序链表();
        ListNode l1 = new ListNode(1);
        ListNode l12 = new ListNode(2);
        ListNode l13 = new ListNode(4);
        ListNode l2 = new ListNode(1);
        ListNode l22 = new ListNode(3);
        ListNode l23 = new ListNode(4);
        l1.next = l12;
        l12.next = l13;
        l2.next = l22;
        l22.next = l23;
        ListNode listNode = inst.mergeTwoLists(l1, l2);
        while (listNode!=null){
            System.out.print(listNode.val);
            listNode = listNode.next;
        }

    }

    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode root = new ListNode();
        ListNode temp = root;
        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                temp.next = list1;
                list1 = list1.next;
            } else {
                temp.next = list2;
                list2 = list2.next;
            }
            temp = temp.next;
        }
        temp.next = list1 == null ? list2 : list1;
        return root.next;
    }
}
